package cn.virens.library.http.callback;

import android.content.Context;
import android.widget.Toast;

import org.xutils.common.Callback;
import org.xutils.ex.HttpException;

import java.net.SocketTimeoutException;

import cn.virens.library.http.response.ResponseException;
import cn.virens.library.uitls.LogUtil;


/**
 * 简单网络响应类
 * Created by loioi on 2017/2/19.
 */
public abstract class HttpCallback<T> implements Callback.CommonCallback<T> {
    protected Context context;

    public HttpCallback(Context context) {
        this.context = context;
    }

    @Override
    public void onSuccess(T result) {
        this.onResult(result);
    }

    @Override
    public void onCancelled(CancelledException cex) {
        Toast.makeText(context, "已取消请求", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (ex instanceof SocketTimeoutException) {
            Toast.makeText(context, "连接超时", Toast.LENGTH_SHORT).show();
            LogUtil.e("连接超时", ex);
        } else if (ex instanceof HttpException) {
            Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
            LogUtil.e("网络错误", ex);
        } else if (ex instanceof ResponseException) {
            Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
            LogUtil.e(ex.getMessage(), ex);
        } else {
            Toast.makeText(context, "未知错误", Toast.LENGTH_SHORT).show();
            LogUtil.e("未知错误", ex);
        }
    }

    @Override
    public void onFinished() {
    }

    public abstract boolean onResult(T result);
}
